package org.atlantis.net.base.vote;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;

/*
 * 投票UDP服务端。
 * 注：UDP服务端接收数据时不需要对数据进行解帧操作，因为UDP的数据报文自带边界标识。
 */
public class VoteServerUDP {

	public static final int SERVER_PORT = 10006;

	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket(SERVER_PORT);
		byte[] buffer = new byte[VoteMessageTextCoder.MAX_WIRE_LENGTH];
		VoteMessageCoder coder = new VoteMessageBinCoder();
		VoteService service = new VoteService();
		while (true) {
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			socket.receive(packet);
			byte[] encodedMessage = Arrays.copyOfRange(packet.getData(), 0,
					packet.getLength());
			System.out.println("Handling request from "
					+ packet.getSocketAddress() + " (" + encodedMessage.length
					+ "bytes).");
			VoteMessage message = coder.decode(encodedMessage);
			message = service.handleRequest(message);
			packet.setData(coder.encode(message));
			socket.send(packet);
		}
	}
}
